const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");

// 删除装车下面的明细销售单据
router.post('/deliver/delCargoItem', async ctx => {
    let tenantId = ctx.user.tenantId;
    let cargoId = ctx.request.body.cargoId;
    let uid = ctx.user.id;
    let iid = ctx.request.body.iid;
    let usr = await db.models['admin'].findOne({
        where: {
            id: uid
        },
        attributes: ['canDelDeliver']
    })
    if (usr.canDelDeliver != 1) {
        return ctx.err('没有删除票据的权限')
    }

    let list = await db.models['cargoInvoice'].findAll({
        where: {
            cargoId: cargoId,
            tenantId: tenantId
        }
    })
    await db.transaction(async () => {
        if (list.length == 1) {
            await db.models['cargoInvoice'].destroy({
                where: {
                    cargoId: cargoId,
                    tenantId: tenantId,
                    iid: iid
                }
            }, )
            await db.models['cargo'].destroy({
                where: {
                    id: cargoId,
                    tenantId: tenantId
                }
            }, )
        }
        else {
            await db.models['cargoInvoice'].destroy({
                where: {
                    cargoId: cargoId,
                    tenantId: tenantId,
                    iid: iid
                }
            }, )
        }
        await db.models['invoice'].update({
            deliverIds: '',
            deliverNames: '',
            isLoad: 0
        }, {
            where:　{
                id: iid
            }
        }, )
    })
    return ctx.suc("已删除 1 条记录");
})

module.exports = router;
